package com.zy.service.fileutil.impl;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.imageio.ImageIO;

import com.zy.service.fileutil.FileBean;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.zy.pojo.exceptions.ServiceException;
import com.zy.service.fileutil.FileUploadService;
import com.zy.utils.CodeUtil;

import net.coobird.thumbnailator.Thumbnails;

@Service("fileUploadService")
public class FileUploadServiceImpl implements FileUploadService {
	protected Logger log = LogManager.getLogger(this.getClass());
	private final String FILE_TYPE = "jpg,jpe, jpeg, bmp,gif, png, psd, swf, svg,htm,css,js";

	@Override
	public String multipleUpload(List<MultipartFile> files, String desPath) throws IllegalStateException, IOException {
		return uploadImage(files, false, null, null, desPath);
	}

	@Override
	public String uploadWithThumbnails(List<MultipartFile> files, Integer height, Integer width, String desPath)
			throws IOException {
		return uploadImage(files, true, height, width, desPath);
	}

	/**
	 * 文件上传切图
	 * 
	 * @param files
	 *            文件
	 * @param thumbnails
	 *            是否切图
	 * @param height
	 *            高
	 * @param width
	 *            宽
	 * @return
	 * @throws IOException
	 */
	private String uploadImage(List<MultipartFile> files, Boolean thumbnails, Integer height, Integer width,
			String desPath) throws IOException {
		// UploadVo uploadVo = new UploadVo();
        if(files.size()<=0){
            throw new ServiceException("请上传图片");
        }
		String fileNames = "";
		Properties pro = PropertiesLoaderUtils.loadAllProperties("config.properties");
		String targetPath = (String) pro.get(desPath);
		for (MultipartFile file : files) {
			String originalFilename = file.getOriginalFilename();
			String ext = FilenameUtils.getExtension(originalFilename);
			String fileName = CodeUtil.getUniqueCode() + "." + ext.toLowerCase();
			Long maxSize = file.getSize();
			if (maxSize > 50 * 1024 * 1024) {
				throw new ServiceException("此视频只支持flv,mp4并为50MB以下");
			}

			if (ext.equals("") || !FILE_TYPE.contains(ext.toLowerCase())) {
				throw new ServiceException("请上传正确的图片格式");
			}

			fileNames += "," + fileName;
			File targetFile = new File(targetPath + fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			file.transferTo(targetFile);
			// System.out.println(cupImages(targetFile));
			if (thumbnails) {
				if (null != height && null != width) {
					Thumbnails.of(targetFile).size(width, height).keepAspectRatio(false).toFile(targetFile);
				}
			}
		}

		return fileNames.substring(1);

	}

	@Override
	public void deleteImage(String img) {
		Properties pro;
		try {
			pro = PropertiesLoaderUtils.loadAllProperties("config.properties");
			String targetPath = (String) pro.get("fileUploadPath");
			File file = new File(targetPath + img);
			if (file.exists()) {
				file.delete();
			} else {
				throw new ServiceException("图片不存在");
			}

		} catch (IOException e) {
			throw new ServiceException("图片不存在");
		}

	}

	/**
	 * 切图
	 * 
	 * @param file
	 * @return
	 */

	public static void main(String[] args) throws Exception {
		// File file = new File("/Users/liu/application/jar/imgs"); //
		// 项目目录下有名为btg.jpg的图片
		// if (!file.exists()) {
		// file.mkdir();
		// }
		System.out.println("ss".toUpperCase());
		// System.out.println(file.getName().substring(0,
		// file.getName().indexOf(".")));
		// FileInputStream fis = new FileInputStream(file);.
		// BufferedImage image = ImageIO.read(fis); // 把文件读到图片缓冲流中
		//
		// int rows = 3; // 定义图片要切分成多少块
		// int cols = 1;
		// int chunks = rows * cols;
		//
		// int chunkWidth = image.getWidth() / cols; // 计算每一块小图片的高度和宽度
		// int chunkHeight = image.getHeight() / rows;
		// int count = 0;
		// BufferedImage imgs[] = new BufferedImage[chunks];
		// for (int x = 0; x < rows; x++) {
		// for (int y = 0; y < cols; y++) {
		// // 初始化BufferedImage
		// imgs[count] = new BufferedImage(chunkWidth, chunkHeight,
		// image.getType());
		//
		// // 画出每一小块图片
		// Graphics2D gr = imgs[count++].createGraphics();
		// gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y,
		// chunkHeight * x,
		// chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
		// gr.dispose();
		// }
		// }
		// System.out.println("切分完成");
		//
		// // 保存小图片到文件中
		// for (int i = 0; i < imgs.length; i++) {
		// ImageIO.write(imgs[i], "JPG", new File("/Users/liu/application/jar/"
		// + i + ".jpg"));
		// }
		// System.out.println("小图片创建完成");

	}

	@Override
	public String cutImage(File file, int rows, int cols, String savePath) {
		String str = "";
		try {
			Properties pro = PropertiesLoaderUtils.loadAllProperties("config.properties");
			String targetPath = (String) pro.get("fileUploadPath");
			String fileName = file.getName();
			String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
			log.info(targetPath + file);
			FileInputStream fis = new FileInputStream(targetPath + file);
			BufferedImage image = ImageIO.read(fis); // 把文件读到图片缓冲流中

			// int rows = 3; //定义图片要切分成多少块
			// int cols = 1;
			int chunks = rows * cols;

			int chunkWidth = image.getWidth() / cols; // 计算每一块小图片的高度和宽度
			int chunkHeight = image.getHeight() / rows;
			int count = 0;
			BufferedImage imgs[] = new BufferedImage[chunks];
			for (int x = 0; x < rows; x++) {
				for (int y = 0; y < cols; y++) {
					// 初始化BufferedImage
					imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

					// 画出每一小块图片
					Graphics2D gr = imgs[count++].createGraphics();
					gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x,
							chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
					gr.dispose();
				}
			}
			// 保存小图片到文件中
			for (int i = 0; i < imgs.length; i++) {
				String code = CodeUtil.getUniqueCode();
				ImageIO.write(imgs[i], prefix.toUpperCase(),
						new File(targetPath + code + i + "." + prefix.toLowerCase()));
				str += "," + code + i + "." + prefix.toLowerCase();
			}

		} catch (Exception e) {
			log.info(e.getMessage(), e);
			throw new ServiceException("图片读取失败");
		}
		return str.substring(1);
	}
	
	@Override
	public String multipleUploadHtm(List<MultipartFile> files, String desPath) throws IllegalStateException, IOException {
		return uploadHtm(files, false, null, null, desPath);
	}
	

	/**
	 * 文件上传htm
	 * 
	 * @param files
	 *            文件
	 * @param thumbnails
	 *            是否切图
	 * @param height
	 *            高
	 * @param width
	 *            宽
	 * @return
	 * @throws IOException
	 */
	private String uploadHtm(List<MultipartFile> files, Boolean thumbnails, Integer height, Integer width,
			String desPath) throws IOException {
		// UploadVo uploadVo = new UploadVo();
		String fileNames = "";
		String targetPath = desPath;
		for (MultipartFile file : files) {
			String originalFilename = file.getOriginalFilename();
			String ext = FilenameUtils.getExtension(originalFilename);
			String fileName = originalFilename;
			Long maxSize = file.getSize();
			if (maxSize > 50 * 1024 * 1024) {
				throw new ServiceException("只支持flv,mp4并为50MB以下");
			}

			if (!FILE_TYPE.contains(ext.toLowerCase())) {
				throw new ServiceException("请上传正确的图片格式");
			}

			fileNames += "," + fileName;
			File targetFile = new File(targetPath + fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			file.transferTo(targetFile);
			// System.out.println(cupImages(targetFile));
			if (thumbnails) {
				if (null != height && null != width) {
					Thumbnails.of(targetFile).size(width, height).keepAspectRatio(false).toFile(targetFile);
				}
			}
		}

		return fileNames.substring(1);

	}

    @Override
    public FileBean fileBeanMultipleUpload(List<MultipartFile> files, String desPath) throws IOException {
        return new FileBean(multipleUpload(files,desPath));
    }
}
